<?php

/**
 * Chatbox model
 *
 * @author     Mon Zafra <monzee at gmail>
 * @copyright  (c)2009 Mon Zafra
 * @category   Mz
 * @package    modules
 * @subpackage chat
 * @license    http://mz-project.googlecode.com/svn/trunk/LICENSE    MIT License
 * @version    SVN: $Id: Chatbox.php 12 2009-02-28 13:39:31Z monzee $
 */
class Chat_Chatbox
{
    static protected $_tableName = 'chat';
    /**
     * @var Zend_Db_Adapter_Abstract
     */
    static protected $_adapter;
    /**
     * @var Zend_Db_Statement
     */
    protected $_result;

    /**
     * Set db adapter on construct.
     * 
     * @param Zend_Db_Adapter_Abstract $adapter 
     */
    public function __construct($adapter = null)
    {
        if (!empty($adapter)) {
            $this->setAdapter($adapter);
        }
    }

    /**
     * Sets the db adapter
     *
     * @param Zend_Db_Adapter_Abstract $adapter
     */
    static public function setAdapter(Zend_Db_Adapter_Abstract $adapter)
    {
        self::$_adapter = $adapter;
    }

    /**
     *
     * @return Zend_Db_Adapter_Abstract
     */
    static public function getAdapter()
    {
        if (null === self::$_adapter) {
            $default = Zend_Db_Table_Abstract::getDefaultAdapter();

            $iniFile = dirname(__FILE__) . '/../config.ini';

            if (!file_exists($iniFile)) {
                self::$_adapter = $default;
            } else {
                $config = new Zend_Config_Ini($iniFile, 'chat');
                $config = $config->db->toArray();

                if (empty($config) || !empty($config['useDefault'])) {
                    return self::$_adapter = $default;
                }

                $adapter = $config['adapter'];
                $params = $config['params'];

                self::$_adapter = Zend_Db::factory($adapter, $params);
            }
        }
        
        return self::$_adapter;
    }

    public function getTableName()
    {
        return self::$_tableName;
    }

    public function setTableName($name)
    {
        if (is_string($name) && '' != $name) {
            self::$_tableName = $name;
        }
    }

    /**
     * Fetches $count rows from the main table ordered by date (descending),
     * returns it in array form. Creates table if not found (sqlite only).
     *
     * @param int $count
     * @return mixed Zend_Db_Statement_Interface or false if the table was
     *               not found
     */
    public function getRecentRows($count = 1)
    {
        $db = $this->getAdapter();
        $sel = $db->select()
            ->from(self::$_tableName, array('name', 'url', 'message', 'date'))
            ->order('date DESC')
            ->limit($count);

        try {
            $this->_result = $db->query($sel);
        } catch (Zend_Db_Statement_Exception $e) {
            $message = $e->getMessage();
            if (false !== strpos($message, 'General error: 1 no such table')) {
                $this->createTable();
                return false;
            }
        }

        return $this->_result;
    }

    /**
     * Adds a row, timestamp added automatically.
     *
     * Creates table if not found (sqlite only).
     * 
     * @param array $values 
     */
    static public function addMessage($values)
    {
        $db = self::getAdapter();
        $table = self::$_tableName;
        $sql = 'INSERT INTO ' . $db->quoteIdentifier($table) . ' (name, url, message, date) '
             . 'VALUES (?, ?, ?, ?);';

        $values = array_values($values);
        $values[] = time();

        try {
            $db->query($sql, $values);
        } catch (Zend_Db_Statement_Exception $e) {
            $message = $e->getMessage();
            if (false !== strpos($message, 'General error: 1 no such table')) {
                self::createTable();
                $db->query($sql, $values);
            }
        }
    }

    /**
     * Create a table if not found.
     *
     * WORKS ONLY FOR PDO_SQLITE ADAPTER
     *
     * @todo Create indexes on date and name
     */
    static public function createTable()
    {
        $table = self::$_tableName;
        $db = self::getAdapter();

        if ($db instanceof Zend_Db_Adapter_Pdo_Sqlite) {
            $sql = 'CREATE TABLE IF NOT EXISTS ' . $db->quoteIdentifier($table) . ' ( '
                 . $db->quoteIdentifier('id') . ' INTEGER PRIMARY KEY, '
                 . $db->quoteIdentifier('name') . ' VARCHAR(32), '
                 . $db->quoteIdentifier('url') . ' VARCHAR(64), '
                 . $db->quoteIdentifier('message') . ' TEXT, '
                 . $db->quoteIdentifier('date') . ' DATETIME )';

            $db->query($sql);
        }
    }

}
